import axios from "axios";
import {MessageBox} from "element-ui";
import VueRouter from "vue-router"

const originalpush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location){
  return originalpush.call(this,location).catch(err=>err)
}


axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
//创建axios实例
const instance = axios.create({
  baseURL:'api',
  // baseURL:'http://localhost:6080',
  timeout:5000
});


//配置请求拦截器，每一个请求携带token
instance.interceptors.request.use(config=>{
  console.log(config);

  //当前端缓存有token存在时，给每个请求携带相应的token信息
  if(localStorage.getItem('token')){
    config.headers.token = localStorage.getItem('token');
  }

  config.withCredentials=false;
  console.log("请求拦截器");
  return config;
});

//响应拦截器
instance.interceptors.response.use(response=>{
  console.log('响应拦截器');
  console.log(response);
  if(response.data.code == 'ERROR'){

    MessageBox.alert(response.data.msg,{
      callback:action => {
        window.location.href = "/"
      }
    })
  }
  return response;


});

//将instance暴露出去
export default instance;
